from django.shortcuts import render
from django.http import JsonResponse
from django.views.generic import ListView
from django.conf import settings
from utils.paginationbase import PaginationBase
from books.models import BookPush
from .models import NewsCategory, NewsNew
import pandas as pd
import os


def main(request):
    context = {
        'hot_books_count': BookPush.objects.all().count()
    }
    return render(request, 'index.html', context=context)


def welcome(request):
    return render(request, 'welcome.html')


class CategoryListView(ListView, PaginationBase):
    model = NewsCategory
    template_name = 'news_category_list.html'
    context_object_name = 'newsCategorys'
    paginate_by = 10
    ordering = '-c_time'
    page_kwarg = 'p'

    def get_context_data(self, **kwargs):
        context = super(CategoryListView, self).get_context_data(**kwargs)
        # context['username'] = 'zhiliao'
        paginator = context.get('paginator')
        page_obj = context.get('page_obj')
        pagination_data = self.get_pagination_data(paginator, page_obj, 3, self.model)
        context.update(pagination_data)
        return context


def to_add_cate(request):
    return render(request, 'news_category_add.html')


def add_cate(request):
    if request.method == 'POST':
        cate_name = request.POST.get('cate_name')
        cate_desc = request.POST.get('cate_desc')
        print('------------------')
        print(cate_name)
        print(cate_desc)
        new_cate = NewsCategory(name=cate_name, desc=cate_desc)
        new_cate.save()
        return JsonResponse({'code': 200, 'msg': '添加成功'})


class NewListView(ListView, PaginationBase):
    model = NewsNew
    template_name = 'news_new_list.html'
    context_object_name = 'news'
    paginate_by = 10
    ordering = 'id'
    page_kwarg = 'p'

    def get_context_data(self, **kwargs):
        context = super(NewListView, self).get_context_data(**kwargs)
        # context['username'] = 'zhiliao'
        paginator = context.get('paginator')
        page_obj = context.get('page_obj')
        pagination_data = self.get_pagination_data(paginator, page_obj, 3, self.model)
        context.update(pagination_data)
        return context


def to_add_data(request):
    return render(request, 'news_new_add.html')


def add_data(request):
    if request.method == 'POST':
        exc_file = request.FILES.get("exc_file")
        # print(exc_file.name, type(exc_file))
        with open(os.path.join(settings.MEDIA_ROOT, 'excel_files', exc_file.name), 'wb') as f:
            for chunk in exc_file.chunks():
                f.write(chunk)
        df = pd.read_excel("{}/excel_files/{}".format(settings.MEDIA_ROOT, exc_file.name))
        # print(df)
        # print(df.columns)
        from .tasks import da_new
        # 调用异步任务da_new
        da_new.delay(df)

        return JsonResponse({'code': 200, 'msg': '导入成功'})
